package lotterysystem.lotterysystem.service.activitystatus.operator;

import jakarta.annotation.Resource;
import lotterysystem.lotterysystem.dao.dataobject.ActivityDO;
import lotterysystem.lotterysystem.dao.mapper.ActivityMapper;
import lotterysystem.lotterysystem.dao.mapper.ActivityPrizeMapper;
import lotterysystem.lotterysystem.service.dto.ConvertActivityStatusDTO;
import lotterysystem.lotterysystem.service.enums.ActivityPrizeStatusEnum;
import lotterysystem.lotterysystem.service.enums.ActivityStatusEnum;
import org.springframework.stereotype.Component;

@Component
public class ActivityOperator extends AbstractActivityOperator{

    @Resource
    private ActivityMapper activityMapper;

    @Resource
    private ActivityPrizeMapper activityPrizeMapper;

    @Override
    public Integer sequence() {
        return 2;
    }

    @Override
    public Boolean needConvert(ConvertActivityStatusDTO convertActivityStatusDTO) {

        Long activityId = convertActivityStatusDTO.getActivityId();
        ActivityStatusEnum targetStatus = convertActivityStatusDTO.getTargetActivityStatus();

        if (null == activityId || null == targetStatus) {

            return false;

        }
        ActivityDO activityDO = activityMapper.selectById(activityId);
        if (null == activityDO) {
            return false;
        }
        //状态是否一致，一致不处理
        if (targetStatus.name().equalsIgnoreCase(activityDO.getStatus())) {
            return false;
        }
        // 判断奖品是否抽完
        // 查询running状态的奖品个数
        int count = activityPrizeMapper.countPrzie(activityId, ActivityPrizeStatusEnum.INIT.name());

        if (count > 0) {
            return false;
        }
        return true;
    }

    @Override
    public Boolean convert(ConvertActivityStatusDTO convertActivityStatusDTO) {
        try {
            activityMapper.updateStatus(convertActivityStatusDTO.getActivityId(),
                    convertActivityStatusDTO.getTargetActivityStatus().name());
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
